#include <iostream>

#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include <unistd.h>

void Usage(const std::string proc)
{
    std::cout << "\n\rUsage: " << proc << " ip " <<"port[1024+]\n" << std::endl;
}

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(-1);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    inet_aton(serverip.c_str(), &(server.sin_addr));

    //创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0)
    {
        std::cout << "socket error" << std::endl;
        exit(1);
    }
    //绑定端口号
    //TCP不需要显示的bind，系统在connet时会自动的bind。
    //因为对于服务端必须有明确的端口号需要被别人知道才能进行通信
    //对于客户端，只保证端口号的唯一性就够了，不需要让别人知道，所以就可以自动生成个随机的端口号bind。

    //发送连接请求
    int n = connect(sockfd, (struct sockaddr*)&server, sizeof(server));
    if(n < 0)
    {
        std::cout << "connect error" << std::endl;
        exit(2);
    }

    std::string message;
    while(true)
    {
        std::cout << "Please Enter# ";
        std::getline(std::cin, message);
        write(sockfd, message.c_str(), message.size());
        
        char inbuffer[4096];
        n = read(sockfd, inbuffer, sizeof(inbuffer));
        if(n > 0)
        {
            inbuffer[n] = 0;
            std::cout << "Server say# " << inbuffer << std::endl;
        }
    }
    return 0;
}